using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 药品订单查询处理器
    /// </summary>
    public class MedicineOrderQueryHandler : IRequestHandler<MedicineOrderQuery, MedicineOrderQueryResult>
    {
        private readonly IConfiguration _configuration;

        public MedicineOrderQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<MedicineOrderQueryResult> Handle(MedicineOrderQuery request, CancellationToken cancellationToken)
        {
            var result = new MedicineOrderQueryResult();
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 构建查询条件
                var conditions = new List<string>();
                var parameters = new DynamicParameters();

                conditions.Add("mo.IsDeleted = 0");

                // 订单号或收货人查询
                if (!string.IsNullOrEmpty(request.OrderSearch))
                {
                    conditions.Add("(mo.OrderNo LIKE @OrderSearch OR mo.Receiver LIKE @OrderSearch)");
                    parameters.Add("@OrderSearch", $"%{request.OrderSearch}%");
                }

                // 提交时间范围查询
                if (request.StartTime.HasValue)
                {
                    conditions.Add("mo.CreateTime >= @StartTime");
                    parameters.Add("@StartTime", request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    conditions.Add("mo.CreateTime <= @EndTime");
                    parameters.Add("@EndTime", request.EndTime.Value.AddDays(1).AddSeconds(-1)); // 结束时间为当天23:59:59
                }

                // 状态查询
                if (request.Status.HasValue && request.Status.Value > 0)
                {
                    // 1：待发货，2：待收货，3：已收货
                    int statusCode = 0;
                    switch (request.Status.Value)
                    {
                        case 1:
                            statusCode = 1; // 待发货状态码
                            break;
                        case 2:
                            statusCode = 2; // 待收货状态码
                            break;
                        case 3:
                            statusCode = 3; // 已收货状态码
                            break;
                    }

                    conditions.Add("mo.Status = @Status");
                    parameters.Add("@Status", statusCode);
                }

                // 构建WHERE子句
                var whereClause = conditions.Count > 0 ? $" WHERE {string.Join(" AND ", conditions)}" : string.Empty;

                // 统计总记录数
                var countSql = @"
                    SELECT COUNT(1) 
                    FROM medicineordermodel mo 
                    LEFT JOIN usermodel u ON mo.UserId = u.Id" + whereClause;
                
                var totalCount = await connection.ExecuteScalarAsync<int>(countSql, parameters);

                // 计算总页数
                int totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                // 分页查询数据
                var offset = (request.PageIndex - 1) * request.PageSize;
                var querySql = @"
                    SELECT 
                        mo.OrderNo, mo.CreateTime AS SubmitTime, u.Phone AS UserPhone, 
                        mo.Receiver, mo.TotalAmount AS OrderAmount, mo.Status
                    FROM medicineordermodel mo
                    LEFT JOIN usermodel u ON mo.UserId = u.Id
                    " + whereClause + @"
                    ORDER BY mo.CreateTime DESC
                    LIMIT @Offset, @PageSize";

                parameters.Add("@Offset", offset);
                parameters.Add("@PageSize", request.PageSize);

                var orders = await connection.QueryAsync<dynamic>(querySql, parameters);

                // 转换为DTO
                var dtoList = orders.Select(o => new MedicineOrderDto
                {
                    OrderNo = o.OrderNo,
                    SubmitTime = o.SubmitTime,
                    UserPhone = o.UserPhone,
                    Receiver = o.Receiver,
                    OrderAmount = o.OrderAmount,
                    Status = ConvertStatus(o.Status)
                }).ToList();

                // 构建结果
                result.TotalCount = totalCount;
                result.TotalPages = totalPages;
                result.CurrentPage = request.PageIndex;
                result.MedicineOrders = dtoList;
            }

            return result;
        }

        /// <summary>
        /// 转换状态码为状态文本
        /// </summary>
        private string ConvertStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "待发货";
                case 2:
                    return "待收货";
                case 3:
                    return "已收货";
                default:
                    return "未知";
            }
        }
    }
} 